<template>
  <div class="lock-screen">
    <div class="lock-box">
      <el-avatar shape="square" :size="40" :src="userAvatar" />
      <span class="lock-nickname">{{ userNickname }}</span>
      <el-input v-model="userPassword" clearable show-password placeholder="请输入密码"></el-input>
      <el-button @click="handleUnlock">解锁</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineEmits, computed, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { verifyPasswordApi } from "../api/user";
const emit = defineEmits(["unlock"]);
const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
const userAvatar = computed(
  () => import.meta.env.VITE_APP_BASE_API + "/public/uploads/" + userInfo.avatar
);
const userNickname = computed(() => userInfo.nickname);
const userPassword = ref("");
const handleUnlock = async () => {
  if (!userPassword.value) {
    ElMessage.warning("请输入密码");
    return;
  }
  try {
    const response: any = await verifyPasswordApi({
      password: userPassword.value,
    });
    if (response.code === 0) {
      emit("unlock", false);
      userPassword.value = "";
    } else {
      ElMessage.error(response.message || "密码错误，请重新输入");
    }
  } catch (error) {
    ElMessage.error("解锁失败，请稍后再试");
  }
};

const handleKeyDown = (event: KeyboardEvent) => {
  if ((event.ctrlKey && event.key === "r") || event.key === "F5") {
    event.preventDefault();
    ElMessage.warning("键盘快捷键已被阻止");
  }
};

// 阻止鼠标右键
const handleContextMenu = (event: MouseEvent) => {
  event.preventDefault();
  ElMessage.warning("鼠标右键已被阻止");
};

// 尝试阻止页面卸载（包括后退和刷新）
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
  event.preventDefault();
  return "";
};

onMounted(() => {
  window.addEventListener("keydown", handleKeyDown);
  document.addEventListener("contextmenu", handleContextMenu);
  window.addEventListener("beforeunload", handleBeforeUnload);
});

onUnmounted(() => {
  window.removeEventListener("keydown", handleKeyDown);
  document.removeEventListener("contextmenu", handleContextMenu);
  window.removeEventListener("beforeunload", handleBeforeUnload);
});
</script>

<style scoped>
.lock-screen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  font-size: 2em;
  z-index: 1000;
}

.lock-box {
  width: 20vw;
  height: 30vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  color: #000;
  font-size: 18px;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
</style>
